package main

import (
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	sc "github.com/hyperledger/fabric/protos/peer"
	"math/rand"
	"strconv"
)

// Define the Smart Contract structure
type SmartContract struct {
}


/*
 * The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network
 * Best practice is to have any Ledger initialization in separate function -- see initLedger()
 */
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
	return shim.Success(nil)
}

func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {

	// Retrieve the requested Smart Contract function and arguments
	function, args := APIstub.GetFunctionAndParameters()
	// Route to the appropriate handler function to interact with the ledger appropriately
	if function == "Get" {
		return s.get(APIstub, args)
	} else if function == "Put" {
		return s.put(APIstub, args)
	}

	return shim.Error("Invalid Smart Contract function name.")
}

func (s *SmartContract) get(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
	i := rand.Int()
	bytes, _ := APIstub.GetState("key" + strconv.Itoa(i))
	fmt.Println("get: key" + strconv.Itoa(i))
	return shim.Success(bytes)
}


func (s *SmartContract) put(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
	i := rand.Int()
	APIstub.PutState("key" + strconv.Itoa(i), []byte(strconv.Itoa(i)))
	fmt.Println("put: key" + strconv.Itoa(i))

	return shim.Success(nil)
}

// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {

	// Create a new Smart Contract
	err := shim.Start(new(SmartContract))
	if err != nil {
		fmt.Printf("Error creating new Smart Contract: %s", err)
	}
}
